using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Microsoft.Extensions.Options;
using System.Text;
using Lzfy_His_Service.Services;
using Lzfy_His_Service.Models;
using Lzfy_His_Service.Models.Configuration;
using Lzfy_His_Service.Repositories;
using Lzfy_His_Service.Middleware;
using Lzfy_His_Service.Extensions;
using Serilog;

// 配置Serilog
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
        .Build())
    .CreateLogger();

try
{
    Log.Information("启动应用程序");
    
    // SSL证书验证将在HttpClient配置中处理
    
    var builder = WebApplication.CreateBuilder(args);
    

    
    // 使用Serilog作为日志提供程序
    builder.Host.UseSerilog();

    // 配置Kestrel服务器选项 - 解决BadHttpRequestException异常
    builder.WebHost.ConfigureKestrel(options =>
    {
        options.Limits.MaxRequestBodySize = 30 * 1024 * 1024; // 30MB请求体大小限制
        options.Limits.RequestHeadersTimeout = TimeSpan.FromMinutes(2); // 请求头超时2分钟
        options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(5); // 保持连接超时5分钟
        options.Limits.MinRequestBodyDataRate = null; // 禁用最小请求数据速率限制
        options.Limits.MinResponseDataRate = null; // 禁用最小响应数据速率限制
    });

// Add services to the container.
builder.Services.AddControllers();

// 配置文件存储选项
builder.Services.Configure<FileStorageOptions>(builder.Configuration.GetSection("FileStorage"));


builder.Services.Configure<HealthCheckOptions>(builder.Configuration.GetSection("HealthCheck"));
builder.Services.Configure<StabilityOptions>(builder.Configuration.GetSection("Stability"));

// 注册数据库配置服务
builder.Services.AddSingleton<IDatabaseConfigurationService, DatabaseConfigurationService>();

// 配置数据库连接工厂 - 使用弹性连接工厂提高稳定性
builder.Services.AddSingleton<IDbConnectionFactory>(provider => 
{
    var dbConfig = provider.GetRequiredService<IDatabaseConfigurationService>();
    var logger = provider.GetRequiredService<ILogger<ResilientSqlConnectionFactory>>();
    return new ResilientSqlConnectionFactory(dbConfig.GetDefaultConnection(), logger);
});

// 配置Oracle HIS数据库连接 - 使用弹性连接工厂提高稳定性
builder.Services.AddSingleton<IOracleConnectionFactory>(provider => 
{
    var dbConfig = provider.GetRequiredService<IDatabaseConfigurationService>();
    var logger = provider.GetRequiredService<ILogger<ResilientOracleConnectionFactory>>();
    return new ResilientOracleConnectionFactory(dbConfig.GetHisOracleConnection(), logger);
});

// 注册连接池优化服务
builder.Services.AddSingleton<OracleConnectionPoolOptimizer>();

// 注册连接泄漏检测器
builder.Services.AddSingleton<ConnectionLeakDetector>();

// 注册优化后的Oracle连接管理器 - 使用工厂化版本
builder.Services.AddScoped<IOracleConnectionManager, FactoryBasedOracleConnectionManager>();

// 配置验证码数据库连接
builder.Services.AddSingleton<IVerifyDbConnectionFactory, VerifyDbConnectionFactory>();

// 注册仓储和服务
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IRefundMasterRepository, RefundMasterRepository>();
builder.Services.AddScoped<IRefundAttachRepository, RefundAttachRepository>();
builder.Services.AddScoped<IRefundDictRepository, RefundDictRepository>();

builder.Services.AddScoped<IVerifyInfoRepository, VerifyInfoRepository>();



// 权限管理相关仓储
builder.Services.AddScoped<IRoleRepository, RoleRepository>();
builder.Services.AddScoped<IPermissionRepository, PermissionRepository>();

// 银行信息管理相关仓储和服务
builder.Services.AddScoped<IBankInfoRepository, BankInfoRepository>();

// 退款审核工作记录相关仓储和服务
builder.Services.AddScoped<IRefundAcctRepository, RefundAcctRepository>();

// 线上退费记录相关仓储
builder.Services.AddScoped<IPrepayRefundDetailRepository, PrepayRefundDetailRepository>();

// UUM用户管理相关仓储
builder.Services.AddScoped<IUumUserRepository, UumUserRepository>();

// 用户基本科室权限查询相关仓储
builder.Services.AddScoped<IUserPermissionRepository, UserPermissionRepository>();

// 退费任务相关仓储
builder.Services.AddScoped<IRefundTaskMasterRepository, RefundTaskMasterRepository>();
builder.Services.AddScoped<IRefundTaskDetailRepository, RefundTaskDetailRepository>();

// 通话记录相关仓储
builder.Services.AddScoped<ICallLogRepository, CallLogRepository>();

// 退费情况查询相关仓储
builder.Services.AddScoped<IRefundStatusRepository, RefundStatusRepository>();

// 电脑软件信息相关仓储
builder.Services.AddScoped<IPcSoftwareRepository, PcSoftwareRepository>();

// 添加内存缓存服务
builder.Services.AddMemoryCache();

// 配置Lazy.Captcha.Core验证码服务
builder.Services.AddCaptcha(builder.Configuration);

// 验证码服务 - 使用LazyCaptcha实现
builder.Services.AddScoped<ICaptchaService, LazyCaptchaService>();

// 登录失败限制服务
builder.Services.AddScoped<ILoginFailureLimitService, LoginFailureLimitService>();

// 服务层
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IRefundService, RefundService>();

builder.Services.AddScoped<IHisPatientBalanceService, HisPatientBalanceService>();
builder.Services.AddScoped<IVerifyInfoService, VerifyInfoService>();
builder.Services.AddScoped<IBankInfoService, BankInfoService>();




// 权限管理相关服务
builder.Services.AddScoped<IRoleService, RoleService>();
builder.Services.AddScoped<IUserManagementService, UserManagementService>();
builder.Services.AddScoped<IPermissionService, PermissionService>();

// 退款审核工作记录服务
builder.Services.AddScoped<IRefundAcctService, RefundAcctService>();

// 线上退费记录服务
builder.Services.AddScoped<IPrepayRefundDetailService, PrepayRefundDetailService>();

// UUM用户管理服务
builder.Services.AddScoped<IUumUserService, UumUserService>();

// 退费任务相关服务
builder.Services.AddScoped<IRefundTaskMasterService, RefundTaskMasterService>();
builder.Services.AddScoped<IRefundTaskDetailService, RefundTaskDetailService>();

// 通话记录相关服务
builder.Services.AddScoped<ICallLogService, CallLogService>();

// 退费情况查询相关服务
builder.Services.AddScoped<IRefundStatusService, RefundStatusService>();

// 退费任务工作量查询服务
builder.Services.AddScoped<IRefundTaskWorkloadService, RefundTaskWorkloadService>();

// 患者退费信息查询服务
builder.Services.AddScoped<IPatientRefundQueryService, PatientRefundQueryService>();

// 患者沟通记录查询服务
builder.Services.AddScoped<IPatientCommunicationService, PatientCommunicationService>();

// 患者卡信息查询服务
builder.Services.AddScoped<IPatientCardInfoService, PatientCardInfoService>();

// 在院病人查询服务
builder.Services.AddScoped<IInpatientService, InpatientService>();



// 坐席账号管理相关服务
builder.Services.AddScoped<IAgentAccountService, AgentAccountService>();

// 账户操作日志相关服务
builder.Services.AddScoped<IAccountOpLogService, AccountOpLogService>();

// 退费任务操作日志相关服务
builder.Services.AddScoped<IRefundTaskOpLogService, RefundTaskOpLogService>();

// 企业微信相关服务
builder.Services.AddWeChatWorkServices(builder.Configuration);

// 用户行为监控相关服务 - 已注释
// builder.Services.AddScoped<IUserBehaviorRepository, UserBehaviorRepository>();
// builder.Services.AddScoped<IUserBehaviorService, UserBehaviorService>();



// 注册后台服务
builder.Services.AddSingleton<ApplicationHealthCheckService>();
builder.Services.AddHostedService<ApplicationHealthCheckService>(provider => provider.GetRequiredService<ApplicationHealthCheckService>());

// 坐席账号清理定时任务服务
builder.Services.AddHostedService<AgentAccountCleanupService>();

// 配置JWT认证
var jwtKey = builder.Configuration["Jwt:Key"] ?? "your-super-secret-jwt-key-that-is-at-least-32-characters-long";
var key = Encoding.ASCII.GetBytes(jwtKey);

builder.Services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ValidateIssuer = false,
        ValidateAudience = false,
        ClockSkew = TimeSpan.Zero
    };
});

// 配置CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowWebAdmin", policy =>
    {
        policy.SetIsOriginAllowed(origin =>
        {
            // 允许空origin（用于Swagger UI等同源请求）
            if (string.IsNullOrEmpty(origin)) return true;
            
            try
            {
                var uri = new Uri(origin);
                var host = uri.Host;
                
                // 允许localhost
                if (host == "localhost" || host == "127.0.0.1")
                    return true;
                    
                // 允许指定的内网IP段
                if (host.StartsWith("10.") || 
                    host.StartsWith("192.168.") || 
                    host.StartsWith("197.100."))
                    return true;
                    
                // 允许指定的域名
                if (host == "his-refund.his.lzsfy.com" || 
                    host.EndsWith(".lzsfy.com") ||
                    host == "www.lzetyy.com" ||
                    host.EndsWith(".lzetyy.com") ||
                    host.EndsWith(".gfelz.com"))

                    return true;
                    
                return false;
            }
            catch
            {
                return false;
            }
        })
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials();
    });
    
    // 添加专门用于Swagger的CORS策略
    options.AddPolicy("AllowSwagger", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "退费申请服务API", Version = "v1" });
    
    // 添加JWT认证配置
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.Http,
        Scheme = "Bearer",
        BearerFormat = "JWT"
    });
    
    // 添加SessionId认证配置
    c.AddSecurityDefinition("SessionId", new OpenApiSecurityScheme
    {
        Description = "Session ID for captcha validation. Example: \"X-Session-Id: your-session-id\"",
        Name = "X-Session-Id",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey
    });
    
    c.AddSecurityRequirement(new OpenApiSecurityRequirement()
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new List<string>()
        },
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "SessionId"
                }
            },
            new List<string>()
        }
    });
});



// 在ConfigureServices部分添加服务
var app = builder.Build();

// Configure the HTTP request pipeline.
// 配置路径前缀（必须在最开始）
app.UsePathBase("/refundtaskapi");

// 启用Swagger在所有环境
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/refundtaskapi/swagger/v1/swagger.json", "退费申请服务API v1");
    c.RoutePrefix = string.Empty; // Swagger UI在根路径，配合UsePathBase使用
});

// app.UseHttpsRedirection(); // 暂时禁用HTTPS重定向

// 启用静态文件服务（用于企业微信验证文件等）
app.UseStaticFiles();

// 使用CORS策略
app.UseCors("AllowWebAdmin");

// 为Swagger UI添加额外的CORS支持
app.Use(async (context, next) =>
{
    if (context.Request.Path.StartsWithSegments("/swagger") ||
        context.Request.Path.StartsWithSegments("/api"))
    {
        context.Response.Headers["Access-Control-Allow-Origin"] = "*";
        context.Response.Headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS";
        context.Response.Headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization";
        
        if (context.Request.Method == "OPTIONS")
        {
            context.Response.StatusCode = 200;
            return;
        }
    }
    await next();
});

// 注册增强的数据库日志记录中间件（必须先于全局异常处理器注册）
app.UseEnhancedDatabaseLogging();
// 注册全局异常处理中间件
app.UseMiddleware<GlobalExceptionHandlingMiddleware>();

// 注册企业微信访问限制中间件（在认证之前）
app.UseWeChatWorkAccessRestriction();

// 配置企业微信服务
app.UseWeChatWorkServices(builder.Environment, builder.Configuration);

app.UseAuthentication();
app.UseAuthorization();

    app.MapControllers();
    Log.Information("服务配置完成，开始启动...");
    
    // 配置监听地址 - 监听所有网络接口以支持外部访问
    var environment = builder.Environment.EnvironmentName;
    var urls = "http://0.0.0.0:6731";
    
    app.Urls.Add(urls);
    Log.Information("服务启动成功！监听地址: {Urls}", urls);
    Console.WriteLine($"\n=== HIS服务启动成功 ===");
    Console.WriteLine($"监听地址: {urls}");
    Console.WriteLine($"环境: {environment}");
    Console.WriteLine($"Swagger文档: {urls}/swagger");
    Console.WriteLine($"启动时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
    Console.WriteLine("=========================\n");
    
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "应用程序启动失败");
    throw;
}
finally
{
    Log.CloseAndFlush();
}